<?php


namespace Modules\Api\Controllers;

use Models\Entities\OffFenyuTables;
use Lib\Response;
use Phalcon\Paginator\Adapter\QueryBuilder;

class FenyuController extends ControllerBase {
	protected $redisPreKey = "ScdataOff_Fenyu_";

	public function listAction() {
		# 第几页
		$page = (int)$this->request->getPost('page', null, 1);
		# 显示条数
		$limit = 20;
		# 查询条件
		$where = 'status!=2';
		$mapper = new OffFenyuTables();
		$request = $this->request;

		# 数据资源目录查询
		$mulu = trim($request->getPost('mulu'));
		# 部门查询
		$departmentName = trim($request->getPost('department_name'));
		# 表名
		$tableName = trim($request->getPost('table_name'));
		# 分类-批次查询
		$pici = trim($request->getPost('pici'));

		if (!empty($mulu)) {
			$where .= ' and mulu="' . $mulu . '"';
		}

		if (!empty($departmentName)) {
			$where .= ' and department_name="' . $departmentName . '"';
		}

		if (!empty($tableName)) {
			$where .= ' and table_name="' . $tableName . '"';
		}

		if (!empty($pici)) {
			$where .= ' and pici="' . $tableName . '"';
		}

		$builder = $mapper->getModelsManager();
		$builder = $builder->createBuilder();
		$builder->where($where);
		$builder->from('Models\Entities\OffFenyuTables');
		$builder->orderBy('fenyu_id DESC, department_name asc');

		$paginator = new QueryBuilder(['builder' => $builder, 'limit' => $limit, 'page' => $page,]);

		$pageObj = $paginator->getPaginate();
		$data = $pageObj->items->toArray();
		$pageData["first"] = $pageObj->first;
		$pageData["before"] = $pageObj->before;
		$pageData["previous"] = $pageObj->previous;
		$pageData["current"] = $pageObj->current;
		$pageData["last"] = $pageObj->last;
		$pageData["next"] = $pageObj->next;
		$pageData["total_pages"] = $pageObj->total_pages;
		$pageData["total_items"] = $pageObj->total_items;
		$pageData["limit"] = $pageObj->limit;

		# 查询出来的结果
		$result["list"] = $data;
		$result["pageData"] = $pageData;

//        foreach ($data as $key => $value) {
//            $data[$key]["nickname"] = urldecode($value["nickname"]);
//        }

		return Response::data($result);
	}

//        # redis
//        $redis = $this->redis;
//        $key = $this->redisPreKey . 'list';
//
//        if ($redis->exists($key)) {
//            $result = $redis->get($key);
//            return \Lib\Response::data(json_decode($result, true));
//        }
//        #

	# redis
//        $redis->set($key, json_encode($result, JSON_UNESCAPED_SLASHES), 86400);

//0-正常 1-禁用 2-删除

	/**
	编辑
	*/
	public function editAction() {
		$time = date("Y-m-d H:i:s");
		$request = $this->request;
		# 取得id值
		# 字符串->trim   整型->int 
		$id = (int)$request->getPost('fenyu_id');
		$mulu = trim((string)$request->getPost('mulu'));
		$departmentName = trim((string)$request->getPost('department_name'));
		$tableName = trim($request->getPost('table_name'));
		$pici = trim($request->getPost('pici'));
		$status = (int)$request->getPost('status');
		$modelData = [];
		$model = '';

		# 有传id值过来
		if ($id > 0) {
			# findFirst->取得一条数据 find->取得所有数据
			$model = OffFenyuTables::findFirst(["status!=2 and fenyu_id=" . $id]);

			if ($model instanceof OffFenyuTables) {
				$modelData = $model->toArray();
			}

			if (empty($modelData)) {
				return Response::error('无此数据');
			}
		}

		# post传值的时候
		if ($request->isPost()) {
			if (empty($mulu)) {
				return Response::error('资源目录不能为空');
			}

			if (empty($departmentName)) {
				return Response::error('部门不能为空');
			}

			if (empty($tableName)) {
				return Response::error('表名不能为空');
			}

			if (empty($pici)) {
				return Response::error('批次不能为空');
			}

			# 无id值->新增数据  有id值->修改数据
			if ($id <= 0 || (!$model instanceof OffFenyuTables)) {
				$model = new OffFenyuTables();
				$model->setCreateTime($time);
				$model->setStatus(0);

			} else {
				$model->setUpdateTime($time);
				$model->setStatus($status);
			}

			$model->setMulu($mulu);
			$model->setDepartmentName($departmentName);
			$model->setTableName($tableName);
			$model->setPici($pici);

			try {
				$result = $model->save();

				if ($result) {
					return Response::data([], '编辑成功');
				} else {
					return Response::error('信息保存失败');
				}
			} catch (\Exception $exc) {
				return Response::error($exc->getMessage());
			}
		}

		return Response::error('请使用POST方式传值');
	}

	# 通过id获取对应的信息
	public function getDataByIdAction() {
		$time = date("Y-m-d H:i:s");
		$request = $this->request;
		$id = (int)$request->getPost('id');

		if ($id <= 0) {
			return Response::error('无此数据');
		}
//            $model = OffFenyuTables::findFirst(["fenyu_id=" . $id, " and status!=2"]);
		$model = OffFenyuTables::findFirst(["status!=2 and fenyu_id=" . $id]);

		if ($model instanceof OffFenyuTables) {
			$modelData = $model->toArray();
		}

		if (empty($modelData)) {
			return Response::error('无此数据');
		}

		return Response::data($modelData);
	}

	# 禁止-1
	public function forbidAction() {
		$time = date("Y-m-d H:i:s");
		$id = (int)$this->request->getPost('id');
		$model = OffFenyuTables::findFirst('fenyu_id=' . $id);

		if (!$model instanceof OffFenyuTables) {
			Response::errmsg('无此数据');
			return false;
		}

		try {
			$model->setUpdateTime($time);
			$model->setStatus(1);

			if ($model->update() === false) {
				return Response::error('禁用失败');
			}

			return Response::data([], '禁用成功');
		} catch (\Exception $e) {
			return Response::errmsg($e->getMessage());
		}
	}

	# 启用-0
	public function resumeAction() {
		$time = date("Y-m-d H:i:s");
		$id = (int)$this->request->getPost('id');
		$model = OffFenyuTables::findFirst('fenyu_id=' . $id);

		if (!$model instanceof OffFenyuTables) {
			Response::errmsg('无此数据');
			return false;
		}

		try {
			$model->setUpdateTime($time);
			$model->setStatus(0);

			if ($model->update() === false) {
				return Response::error('恢复失败');
			}

			return Response::data([], '恢复成功');
		} catch (\Exception $e) {
			return Response::errmsg($e->getMessage());
		}
	}

	# 删除-3
	public function delAction() {
		$time = date("Y-m-d H:i:s");
		$id = (int)$this->request->getPost('id');
		$model = OffFenyuTables::findFirst('fenyu_id=' . $id);
		# 测试语句
		#var_dump($model->toArray);die();

		if (!$model instanceof OffFenyuTables) {
			Response::errmsg('无此数据');
			return false;
		}

		try {
			$model->setUpdateTime($time);
			$model->setStatus(2);

			if ($model->update() === false) {
				return Response::error('删除失败');
			}

			return Response::data([], '编辑成功');
		} catch (\Exception $e) {
			return Response::errmsg($e->getMessage());
		}
	}


}
